//
//  TRsearchViewController.m
//  WeiMiLan
//
//  Created by cong on 14-8-2.
//  Copyright (c) 2014年 Mac. All rights reserved.
//

#import "TRsearchViewController.h"
#import "PullCollectionView.h"
#import "TRMemuCell.h"
#import "TRNewsGoodsViewController.h"
@interface TRsearchViewController ()
@property(nonatomic,strong)NSMutableArray * searchArray;
@property(nonatomic,strong)NSMutableArray * idArray;

@property (strong, nonatomic) PullCollectionView *collectionView;


@property(nonatomic,assign)int  pageNum;
@property(nonatomic,assign)NSInteger oldNum;

@property(strong,nonatomic)NSString * CATEGORY;
@property(nonatomic,strong)NSDictionary * pageDict;
@end

@implementation TRsearchViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)gotoMainPage
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark-----男女试图
- (void)initNavigation
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.weChatNavigationBar=[[WeChatNavigationBar alloc] init];
    [self.view addSubview:self.weChatNavigationBar];
    //    self.weChatNavigationBar.titleLabel.text=self.album[0][@"NAME"];
    
    self.weChatNavigationBar.titleLabel.text=@"搜索";
    [self.weChatNavigationBar .leftButton addTarget:self action:@selector(gotoMainPage)  forControlEvents:UIControlEventTouchUpInside];
    self.weChatNavigationBar.rightButton.hidden = NO;
    
     [self.weChatNavigationBar.rightButton setImage:[UIImage imageNamed:@"rli(1)"] forState:0];

    [self.weChatNavigationBar.rightButton addTarget:self action:@selector(showDateVC) forControlEvents:UIControlEventTouchUpInside];
   // self.weChatNavigationBar.rightButton.center = self.weChatNavigationBar.center;
    self.weChatNavigationBar.rightButton.origin = CGPointMake(self.view.width - 32, self.weChatNavigationBar.rightButton.origin.y );
    self.weChatNavigationBar.rightButton.width = 22;
    self.weChatNavigationBar.rightButton.height = 22;
//    
//    _tb=[[TableViewWithBlock alloc] initWithFrame:CGRectMake(kUI_SCREEN_WIDTH-105, 70, 100, 136)];
//    
//    
//    _tb.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"rli"]];
//    _tb.layer.borderWidth=4.0f;
//    _tb.layer.borderColor=[[UIColor blackColor] CGColor];
//    _tb.delegate=self;
//    [ApplicationDelegate.window addSubview:_tb];
//    _tb.hidden=YES;
}
- (void)showDateVC {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    TRNewsGoodsViewController *TVC=[sb instantiateViewControllerWithIdentifier:@"TRNewsGoodsViewController"];
    [self.navigationController pushViewController:TVC animated:YES];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.CATEGORY=@"";
    
    CHTCollectionViewWaterfallLayout *layout = [[CHTCollectionViewWaterfallLayout alloc] init];
    
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    layout.headerHeight = 0;
    layout.footerHeight = 0;
//    layout.minimumColumnSpacing = 10;
//    layout.minimumInteritemSpacing = 10;
    layout.columnCount = 1;
    CGRect r = CGRectMake(0, 64, self.view.bounds.size.width, self.view.bounds.size.height-44);
    //包包
    self.collectionView=[[PullCollectionView alloc] initWithFrame:r collectionViewLayout:layout];
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"TRMemuCell" bundle:nil] forCellWithReuseIdentifier:@"TRMemuCell"];
    
    self.collectionView.pullBackgroundColor = [UIColor whiteColor];
    self.collectionView.pullTextColor = [UIColor blackColor];

    self.collectionView.dataSource=self;
    self.collectionView.delegate=self;
    self.collectionView.pullDelegate = self;
    [self.view addSubview:self.collectionView];
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    [self initNavigation];
    
    self.pageNum=1;
    
    self.searchArray = [@[]mutableCopy];
    self.idArray = [@[]mutableCopy];
    [self.collectionView beginRefresh];
    
    [self initSeachButton];
}

#pragma mark - PullCollectionViewDelegate
-(void)pullCollectionViewDidTriggerRefresh:(PullCollectionView *)pullCollectionView{
    [pullCollectionView endRefreshing];
    self.CATEGORY=@"";
    [self initData:1];
}

-(void)reflushNow{
    [self.collectionView endRefreshing];
    [self.collectionView endLoadingMore];
}

- (void)pullCollectionViewDidTriggerLoadMore:(PullCollectionView*)pullCollectionView{
    [pullCollectionView endRefreshing];
    [self performSelector:@selector(reflushNow) withObject:nil afterDelay:2.];
    
    NSLog(@"页码：%@",self.pageDict);
    [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"%d/%@",[self.pageDict[@"NUMBER"] intValue]+1,self.pageDict[@"PAGES"]]];
    if (self.pageDict) {
        
        
        if ([self.pageDict[@"NUMBER"] intValue] == [self.pageDict[@"PAGES"] intValue]) {
            
            [SVProgressHUD showImage:nil status:@"已无更多"];
            return;
        }
    }
    [self initData:[self.pageDict[@"NEXT"] intValue]];
}

#pragma mark-----隐藏男女视图
-(void)showTB
{
    
    NSLog(@"======");
    if (_tb.hidden==YES) {
        _tb.hidden=NO;
    }else
    {
        _tb.hidden=YES;
        
    }
    
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.collectionView.pullDelegate=self;
    
}
#pragma mark------男女视图
-(void)initSeachButton
{
    //_isOpened=NO;
    [_tb initTableViewDataSourceAndDelegate:^(UITableView *tableView,NSInteger section){
        
        return (NSInteger)3;
        
    } setCellForIndexPathBlock:^(UITableView *tableView,NSIndexPath *indexPath){
        SelectionCell *cell=[tableView dequeueReusableCellWithIdentifier:@"SelectionCell"];
        if (!cell) {
            cell=[[[NSBundle mainBundle]loadNibNamed:@"SelectionCell" owner:self options:nil]objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        
        cell.lb.backgroundColor=[UIColor clearColor];
        cell.img.backgroundColor=[UIColor clearColor];
        cell.backgroundColor=[UIColor clearColor];
        cell.contentView.backgroundColor=[UIColor clearColor];
        UIView *v=[[UIView alloc] init];
        v.backgroundColor=[UIColor clearColor];
        cell.selectedBackgroundView=v;
        //        cell.lb.text=@[@"",@"男",@"女"][indexPath.row];
        //        if (indexPath.row==0) {
        //            cell.img.image=[UIImage imageNamed:@"timeImage"];
        //        }
        
        return cell;
    } setDidSelectRowBlock:^(UITableView *tableView,NSIndexPath *indexPath){
        //SelectionCell *cell=(SelectionCell*)[tableView cellForRowAtIndexPath:indexPath];
        
        
        //        _inputTextField.text=cell.lb.text;
        //        self.selectIndex=indexPath.row;
        //        [_openButton sendActionsForControlEvents:UIControlEventTouchUpInside];
        switch (indexPath.row) {
            case 0:
            {
                
                TRNewsGoodsViewController *TVC=[self.storyboard instantiateViewControllerWithIdentifier:@"TRNewsGoodsViewController"];
                [self.navigationController pushViewController:TVC animated:YES];
                
                // [self performSegueWithIdentifier:@"toNewGood" sender:nil];
                
                
            }
                break;
            case 1:
            {
                
                self.CATEGORY=@"1";
                
                [self initData:1];
            }
                break;
            case 2:
            {
                
                self.CATEGORY=@"0";
                
                [self initData:1];
            }
                break;
                
            default:
                break;
        }
        
        
        _tb.hidden=YES;
        
        
        
    }];
    
    [_tb.layer setBorderColor:[UIColor lightGrayColor].CGColor];
    [_tb.layer setBorderWidth:2];
    
}


-(void)initData:(NSInteger)pageNum{
    NSString *URLTmp;
    NSString *userId=ApplicationDelegate.currentUserId;
    if ([NSString isBlankString:ApplicationDelegate.markString]) {
        URLTmp = [NSString stringWithFormat:@"http://ping.vsmu.cn/app/Interface/Package?type=1010&userId=%@&NAME=%@&%@=%ld&ID=%@&CATEGORY=%@",userId,self.searchString,PAGE_NUM,pageNum,self.searchInString,self.CATEGORY];
    }else
    {
        
        URLTmp = [NSString stringWithFormat:@"http://ping.vsmu.cn/app/Interface/Package?type=1010&userId=%@&NAME=%@&BRANDID=%@&%@=%ld&ID=%@&CATEGORY=%@",userId,self.searchString,ApplicationDelegate.markString,PAGE_NUM,pageNum,self.searchInString,self.CATEGORY];
    }
    NSString * requestString = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  //转码成UTF-8  否则可能会出现错误
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: requestString]];
    
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.collectionView endRefreshing];
        if (pageNum==1) {
            self.searchArray=[NSMutableArray array];
        }
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        //系统自带JSON解析
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
        
       // NSLog(@"搜索信息:%@",[NSString replaceUnicode:resultDic.description]);
        self.pageDict = resultDic[@"PAGE_INFO"];
        
        NSString * msg = resultDic[@"MESSAGE_INFO"][@"MESSAGE"];
        
        //        self.searchArray = [NSMutableArray arrayWithArray:resultDic[@"PACKAGE_RSP"][@"PACKAGE"]];
        for (NSDictionary * idName in resultDic[@"PACKAGE_RSP"][@"PACKAGE"]) {
            if (![self.idArray containsObject:idName[@"ID"]]) {
                [self.searchArray addObject:idName];
                [self.idArray containsObject:idName[@"ID"]];
            }
        }
        if (self.searchArray.count==0) {
            MMProgressHUDShowSuccess(@"没发现符合条件的产品");
        }
        [self.collectionView reloadData];
        if (msg.length>2) {
            MMProgressHUDShowSuccess(msg);
        }else{
           
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.collectionView endRefreshing];
        NSLog(@"Failure: %@",error);
        
        MMProgressHUDShowError(@"提交失败，请重试");
        
    }];
    [operation start];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    _tb.hidden=YES;
    [self.collectionView setPullDelegate:nil];
    
}

- (void)viewDidUnload
{
    [self setCollectionView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

#pragma mark - collectview部分
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TRMemuCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"TRMemuCell" forIndexPath:indexPath];
    cell.backgroundColor=[UIColor grayColor];

    if(cell == nil) {
        NSArray *nib =
        [[NSBundle mainBundle] loadNibNamed:@"TRMemuCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    cell.info = [self.searchArray objectAtIndex:indexPath.row];
   // cell.selectImageView.hidden= YES;
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    TRProductDetailViewController *vc = [[TRProductDetailViewController alloc] init];
    vc.productTypeId = self.searchArray[indexPath.row][@"ID"];
    [self presentViewController:vc animated:YES completion:nil];
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    self.oldNum =self.searchArray.count;
    return self.searchArray.count;
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSArray * goods = self.searchArray;
    TRMemuCell *cell =[[TRMemuCell alloc] init];
    cell.info = [goods objectAtIndex:indexPath.row];
    return [cell getSize];
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 2;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 2;
}

@end
